#!/usr/bin/python

import gedit
import gtk
from gettext import gettext as _

ui_string ='''
<ui>
 <menubar name="MenuBar">
  <menu name="ToolsMenu" action="Tools">
   <placeholder name="ToolsOps_2">
    <menuitem name="dummy menu action" action="GNU-style"/>
   </placeholder>
  </menu>
 </menubar>
</ui>
'''


class AppWindow:
    def __init__(self, plugin, window):

        self._window = window
        self._plugin = plugin
        
        #start keypress event !
        self._handler = self._window.connect('key_press_event',self.KeyPressHandler)
        
        #inserting the menu here
        self.InsertMenu()
        
        self._indentations = [0]

        self._colon_flag = False
    def deactivate(self):
                #remove the menu items here
                self.RemoveMenu()
               
                #remove the key_press_event
                self._window.disconnect(self._handler)

                #set all parameters to null
                self._window = None
                self._plugin = None
                self._action_group = None


    def InsertMenu(self):
        # get gedit's window manager
        _manager = self._window.get_ui_manager()
        
        #create a new ActionGroup for the window
        self._action_group = gtk.ActionGroup("Code Format")
        
        #add actions to the action group
        _actions = []
        _actions = _actions + [('dummy menu action',None,_("Gnu"),None,_('this menu item does nothin'),self.Indent )]
        
        self._action_group.add_actions(_actions)
        
        #now add this action group to gedit UIManager
        _manager.insert_action_group(self._action_group,-1)
        self._ui_id = _manager.add_ui_from_string(ui_string)
               
        return
               
    def RemoveMenu(self):
        #first get the gedit UI manager
        _manager = self._window.get_ui_manager()
        
        #now remove the UI menu and the user menu added !
        _manager.remove_ui(self._ui_id)
        _manager.remove_action_group(self._action_group)
        _manager.ensure_update()
        
        return

       
    def update_ui(self):
        self._action_group.set_sensitive(self._window.get_active_document() != None )
        return
    
    def Indent(self,action):
        doc = self._window.get_active_document()
        tab = self._window.get_active_tab()
        if not doc :
            return
        return


    def KeyPressHandler(self,widget,event,data=None):
       '''
       this is the main event handler for the python indenter 
       
       rite now there are keypress handles for three key presses 
       1) Return key : when pressed gets the indentation of the last line ! 
       2) colon key : increases the indentation level by 1 
       3) Tab key: this iterates the current level of indentation in all possible locations ! 
       '''


       #print gtk.gdk.keyval_name(event.keyval)

       _flag = False
       _text_buffer = self._window.get_active_document()
       
       #find the current line number and set the indentation same as the last line !
       _line = self.get_line_number() 
       
       
       if gtk.gdk.keyval_name( event.keyval ) == 'Return':
           
           #do the action and set flag to true so that the event is not propogated !
           _text_buffer.insert_at_cursor('\n')
           _flag = True
           
           self._indentations = self._indentations + [ 0 ]

           #create the indentation for this line
           if self._colon_flag == True :
               
               # if a colon has been pressed then the indentations is incremented by one ! 
               self._indentations[-1] = self._indentations[-1] + self.get_indentation( _line ) + 1
               
               # now set the colon flag to be zero 
               self._colon_flag = False
           
           else :
              
               self._indentations[-1] = self._indentations[-1] + self.get_indentation( _line ) 
           
           #now set the indentation
           self.set_line_indentation( self._indentations[-1] )
           #print self._indentations[-1]
           
           
       elif gtk.gdk.keyval_name( event.keyval ) == 'colon':
           self._colon_flag = True
              
       return _flag
       
    def set_line_indentation( self , count ):
        tabs = ''
        for i in range(count):
            tabs = tabs + '\t'

        _text_buffer = self._window.get_active_document()
        _text_buffer.insert_at_cursor(tabs)
        
        return

    def get_line_number(self):
        _text_buffer = self._window.get_active_document()
        _current_mark = _text_buffer.get_insert()
        _text_iterator = _text_buffer.get_iter_at_mark( _current_mark )
        return _text_iterator.get_line()

    def get_indentation(self,line):
        _text_buffer = self._window.get_active_document()
        _iter = _text_buffer.get_iter_at_line( line  )
        
        _count = 0
        while _iter.get_char() == '\t':
            _count = _count + 1
            _iter.forward_char()
        
        return _count
       
    def actual_count(self,arr):
        count = 0
        for i in range(len(arr)):
            if self.colon_end [i] == '-' :
                break
        return count
           
class AppPlugin(gedit.Plugin):
    def __init__(self):
        gedit.Plugin.__init__(self)
        self._instances = {}

    def activate(self, window):
        self._instances[window] = AppWindow(self, window)

    def deactivate(self, window):
        self._instances[window].deactivate()
        del self._instances[window]

    def update_ui(self, window):
        self._instances[window].update_ui()


